package com.example.appusagestats

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import android.view.View
import com.example.appusagestats.adapter.AppUsageAdapter
import com.example.appusagestats.manager.AppUsageStatsManager
import com.example.appusagestats.model.AppUsageInfo
import kotlinx.coroutines.*
import android.view.KeyEvent
import android.os.Handler
import android.os.Looper
import android.os.Build

class MainActivity : AppCompatActivity() {

    private lateinit var usageStatsManager: AppUsageStatsManager
    private lateinit var appUsageAdapter: AppUsageAdapter
    private lateinit var appUsageRecyclerView: RecyclerView
    private lateinit var emptyText: TextView
    private lateinit var sortButton: Button
    private lateinit var refreshButton: Button
    private lateinit var timeSlotButton: Button

    private var isSortByTime = true
    private var appUsageList = listOf<AppUsageInfo>()
    private val coroutineScope = CoroutineScope(Dispatchers.Main + SupervisorJob())

    // 按键检测相关变量
    private val keyHoldDetector = KeyHoldDetector()
    private var keyDownTime = 0L

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        try {
            initViews()
            initUsageStatsManager()
            setupRecyclerView()
            setupClickListeners()
            checkPermissionAndLoadData()
        } catch (e: Exception) {
            Log.e("MainActivity", "onCreate error", e)
            Toast.makeText(this, "初始化失败: ${e.message}", Toast.LENGTH_SHORT).show()
        }
    }

    override fun onResume() {
        super.onResume()
        try {
            if (::usageStatsManager.isInitialized && usageStatsManager.hasUsageStatsPermission()) {
                loadAppUsageData()
            }
        } catch (e: Exception) {
            Log.e("MainActivity", "onResume error", e)
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        coroutineScope.cancel()
    }

    private fun initViews() {
        try {
            appUsageRecyclerView = findViewById(R.id.appUsageRecyclerView)
            emptyText = findViewById(R.id.emptyText)
            sortButton = findViewById(R.id.sortButton)
            refreshButton = findViewById(R.id.refreshButton)
            timeSlotButton = findViewById(R.id.timeSlotButton)
        } catch (e: Exception) {
            Log.e("MainActivity", "initViews error", e)
            throw e
        }
    }

    private fun initUsageStatsManager() {
        try {
            usageStatsManager = AppUsageStatsManager(this)
        } catch (e: Exception) {
            Log.e("MainActivity", "initUsageStatsManager error", e)
            throw e
        }
    }

    private fun setupRecyclerView() {
        try {
            appUsageAdapter = AppUsageAdapter(emptyList()) { appUsage ->
                try {
                    val intent = Intent(this, AppDetailActivity::class.java).apply {
                        putExtra("package_name", appUsage.packageName)
                        putExtra("app_name", appUsage.appName)
                    }
                    startActivity(intent)
                } catch (e: Exception) {
                    Log.e("MainActivity", "startActivity error", e)
                    Toast.makeText(this, "打开应用详情失败", Toast.LENGTH_SHORT).show()
                }
            }

            appUsageRecyclerView.apply {
                layoutManager = LinearLayoutManager(this@MainActivity)
                adapter = appUsageAdapter
            }
        } catch (e: Exception) {
            Log.e("MainActivity", "setupRecyclerView error", e)
            throw e
        }
    }

    private fun setupClickListeners() {
        try {
            sortButton.setOnClickListener {
                try {
                    isSortByTime = !isSortByTime
                    if (isSortByTime) {
                        sortButton.text = getString(R.string.sort_by_time)
                        appUsageAdapter.sortByTime()
                    } else {
                        sortButton.text = getString(R.string.sort_by_name)
                        appUsageAdapter.sortByName()
                    }
                } catch (e: Exception) {
                    Log.e("MainActivity", "sortButton click error", e)
                    Toast.makeText(this, "排序失败", Toast.LENGTH_SHORT).show()
                }
            }

            refreshButton.setOnClickListener {
                loadAppUsageData()
            }

            timeSlotButton.setOnClickListener {
                try {
                    val intent = Intent(this, TimeSlotActivity::class.java)
                    startActivity(intent)
                } catch (e: Exception) {
                    Log.e("MainActivity", "timeSlotButton click error", e)
                    Toast.makeText(this, "打开时间段查看失败", Toast.LENGTH_SHORT).show()
                }
            }
        } catch (e: Exception) {
            Log.e("MainActivity", "setupClickListeners error", e)
            throw e
        }
    }

    private fun checkPermissionAndLoadData() {
        try {
            if (!usageStatsManager.hasUsageStatsPermission()) {
                showPermissionDialog()
            } else {
                loadAppUsageData()
            }
        } catch (e: Exception) {
            Log.e("MainActivity", "checkPermissionAndLoadData error", e)
            Toast.makeText(this, "权限检查失败", Toast.LENGTH_SHORT).show()
        }
    }

    private fun showPermissionDialog() {
        try {
            AlertDialog.Builder(this)
                .setTitle(R.string.permission_required)
                .setMessage(R.string.permission_message)
                .setPositiveButton(R.string.grant_permission) { _, _ ->
                    try {
                        usageStatsManager.requestUsageStatsPermission()
                    } catch (e: Exception) {
                        Log.e("MainActivity", "requestPermission error", e)
                        Toast.makeText(this, "请求权限失败", Toast.LENGTH_SHORT).show()
                    }
                }
                .setNegativeButton(R.string.cancel) { dialog, _ ->
                    dialog.dismiss()
                }
                .setCancelable(false)
                .show()
        } catch (e: Exception) {
            Log.e("MainActivity", "showPermissionDialog error", e)
        }
    }

    private fun loadAppUsageData() {
        coroutineScope.launch {
            try {
                val data = withContext(Dispatchers.IO) {
                    usageStatsManager.getTodayAppUsageStats()
                }
                
                appUsageList = data
                updateUI(data)
            } catch (e: Exception) {
                Log.e("MainActivity", "loadAppUsageData error", e)
                withContext(Dispatchers.Main) {
                    Toast.makeText(this@MainActivity, "加载数据失败: ${e.message}", Toast.LENGTH_SHORT).show()
                    updateUI(emptyList())
                }
            }
        }
    }

    private fun updateUI(data: List<AppUsageInfo>) {
        try {
            if (data.isEmpty()) {
                emptyText.visibility = View.VISIBLE
                appUsageRecyclerView.visibility = View.GONE
            } else {
                emptyText.visibility = View.GONE
                appUsageRecyclerView.visibility = View.VISIBLE
                appUsageAdapter.updateData(data)
            }
        } catch (e: Exception) {
            Log.e("MainActivity", "updateUI error", e)
            Toast.makeText(this, "更新界面失败", Toast.LENGTH_SHORT).show()
        }
    }

    // 检测按键按住的重写方法
    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_UP,
            KeyEvent.KEYCODE_VOLUME_DOWN,
            KeyEvent.KEYCODE_BACK,
            KeyEvent.KEYCODE_MENU -> {
                keyDownTime = System.currentTimeMillis()
                Log.d("KeyHold", "Key pressed: $keyCode")
                
                // 使用自己实现的按键按住检测
                keyHoldDetector.detectKeyHold(keyCode) { repeatedKeyCode ->
                    onKeyHoldRepeat(repeatedKeyCode)
                }
                
                // 使用repeatCount检测按键重复 (兼容所有API版本)
                if (event != null && event.repeatCount > 0) {
                    Log.d("KeyHold", "Key repeated by system: $keyCode (repeatCount: ${event.repeatCount})")
                    Toast.makeText(this, "按键 $keyCode 被按住", Toast.LENGTH_SHORT).show()
                }
                return true
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun onKeyUp(keyCode: Int, event: KeyEvent?): Boolean {
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_UP,
            KeyEvent.KEYCODE_VOLUME_DOWN,
            KeyEvent.KEYCODE_BACK,
            KeyEvent.KEYCODE_MENU -> {
                val holdDuration = System.currentTimeMillis() - keyDownTime
                Log.d("KeyHold", "Key released: $keyCode, held for: ${holdDuration}ms")
                
                // 停止按键按住检测
                keyHoldDetector.onKeyUp(keyCode)
                
                if (holdDuration > 500) {
                    Toast.makeText(this, "按键 $keyCode 被按住 ${holdDuration}毫秒", Toast.LENGTH_SHORT).show()
                }
                return true
            }
        }
        return super.onKeyUp(keyCode, event)
    }

    // 处理按键重复时的回调
    private fun onKeyHoldRepeat(keyCode: Int) {
        Log.d("KeyHold", "Detected key hold repeat: $keyCode")
        Toast.makeText(this, "检测到按键 $keyCode 被按住", Toast.LENGTH_SHORT).show()
        
        // 可以在这里添加具体的按键按住处理逻辑
        when (keyCode) {
            KeyEvent.KEYCODE_VOLUME_UP -> {
                // 音量上键被按住的处理
            }
            KeyEvent.KEYCODE_VOLUME_DOWN -> {
                // 音量下键被按住的处理  
            }
            KeyEvent.KEYCODE_BACK -> {
                // 返回键被按住的处理
            }
            KeyEvent.KEYCODE_MENU -> {
                // 菜单键被按住的处理
            }
        }
    }
} 

// 按键按住检测器类
class KeyHoldDetector {
    private val handlers = mutableMapOf<Int, KeyHandler>()
    private val mainHandler = Handler(Looper.getMainLooper())
    
    data class KeyHandler(
        var isPressed: Boolean = false,
        var pressTime: Long = 0,
        var repeatRunnable: Runnable? = null
    )
    
    fun detectKeyHold(keyCode: Int, onRepeat: (Int) -> Unit) {
        val handler = handlers.getOrPut(keyCode) { KeyHandler() }
        
        if (!handler.isPressed) {
            handler.isPressed = true
            handler.pressTime = System.currentTimeMillis()
            
            // 延迟500ms后开始检测重复
            handler.repeatRunnable = object : Runnable {
                override fun run() {
                    if (handler.isPressed) {
                        val holdTime = System.currentTimeMillis() - handler.pressTime
                        if (holdTime >= 500) {
                            onRepeat(keyCode)
                            Log.d("KeyHold", "Key $keyCode held for ${holdTime}ms")
                        }
                        mainHandler.postDelayed(this, 200) // 每200ms检查一次
                    }
                }
            }
            mainHandler.postDelayed(handler.repeatRunnable!!, 500)
        }
    }
    
    fun onKeyUp(keyCode: Int) {
        handlers[keyCode]?.let { handler ->
            handler.isPressed = false
            handler.repeatRunnable?.let { 
                mainHandler.removeCallbacks(it)
            }
            handler.repeatRunnable = null
        }
    }
}